package sample;

public class Edge
{
	private Vertex source;
	private Vertex target;

	public Edge()
	{
		source = new Vertex();
		target = new Vertex();
	}

	public Edge(Vertex source, Vertex target)
	{
		this.source = source;
		this.target = target;
	}

	public Vertex getSource()
	{
		return source;
	}

	public void setSource(Vertex source)
	{
		this.source = source;
	}

	public Vertex getTarget()
	{
		return target;
	}

	public void setTarget(Vertex target)
	{
		this.target = target;
	}

	public String toString()
	{
		return " (" + source.getIndex() + "," + target.getIndex() + ") ";
		// return
		// " ("+source.getIndex()+"-> ("+source.getX()+","+source.getY()+"),("+target.getIndex()+"-> ("+target.getX()+","+target.getY()+") ";
	}

	public boolean equals(Object o)
	{
		Edge e = (Edge)o;
		if ((this.source.equals(e.source) && this.target.equals(e.target))
				|| (this.source.equals(e.target) && this.target
						.equals(e.source)))
			return true;
		return false;

	}

	public double[] calculateLineEquation()
	{
		double[] result = new double[2];

		// m
		result[0] = (source.getY() * 1.0 - target.getY())
				/ ((source.getX() * 1.0 - target.getX()) + 0.00001);

		if (result[0] > 1000)
		{
			result[1] = 0;
		}
		else
			result[1] = source.getY() * 1.0 - result[0] * source.getX();

		return result;
	}

	public double getLength()
	{
		return Math.sqrt(Math.pow(getSource().getX() - getTarget().getX(), 2)
				+ Math.pow(getSource().getY() - getTarget().getY(), 2));
	}
	
	/**
	 * Finds the common vertex between two edges. Returns null if there is no common vertex.
	 * @param e
	 * @return
	 */
	public Vertex getCommonVertex(Edge e)
	{
		// find their common vertex
		Vertex common = new Vertex();
		if (this.getSource().equals(e.getSource())
				|| this.getSource().equals(e.getTarget()))
			common = this.getSource();
		else if (this.getTarget().equals(e.getSource())
				|| this.getTarget().equals(e.getTarget()))
			common = this.getTarget();
		else
			common = null;
		
		return common;
	}
	
	public Vertex getOtherEnd(Vertex v)
	{
		if(this.getSource().equals(v))
			return this.getTarget();
		else if(this.getTarget().equals(v))
			return this.getSource();
		else
			return null;
	}
}
